package com.qf.mybatisplus.service.impl;

import com.qf.mybatisplus.bean.po.ProvinceCityCounty;
import com.qf.mybatisplus.mapper.ProvinceCityCountyMapper;
import com.qf.mybatisplus.resultBean.Result;
import com.qf.mybatisplus.service.ProvinceCityCountyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description: TODO
 * @projectName: my-project
 * @package: com.qf.mybatisplus.service.impl
 * @className: ProvinceCityCountyImpl
 * @author: zdd
 * @date: 2024/11/6 16:25
 * @version: 1.0
 */
@Service
public class ProvinceCityCountyImpl implements ProvinceCityCountyService {


    @Autowired
    private ProvinceCityCountyMapper provinceCityCountyMapper;

    /**
     * 获取省市区树形列表
     * @param province
     * @return
     */
    @Override
    public Result getProvinceCityCountyList(String province) {
        Result result = new Result();


        // 查询省
        List<ProvinceCityCounty> provinceList = provinceCityCountyMapper.getProvinceList(province);
        // 查询市
        List<ProvinceCityCounty> cityList = provinceCityCountyMapper.getCityList();
        // 查询区
        List<ProvinceCityCounty> countryList = provinceCityCountyMapper.getCountyList();
//        写法1
//        for (ProvinceCityCounty ProvinceCityCounty : provinceList) {
//            List<ProvinceCityCounty> childrenCityList = cityList.stream().filter(city -> city.getParentId().equals(ProvinceCityCounty.getId())).collect(Collectors.toList());
//            for (ProvinceCityCounty cityCountry : childrenCityList) {
//                List<ProvinceCityCounty> childrenCountryList = countryList.stream().filter(country -> country.getParentId().equals(cityCountry.getId())).collect(Collectors.toList());
//                cityCountry.setProvinceCityCountyList(childrenCountryList);
//            }
//            ProvinceCityCounty.setProvinceCityCountyList(childrenCityList);
//        }


        // 写法2
        Optional.ofNullable(provinceList).orElse(new ArrayList<>()).forEach(ProvinceCityCounty ->{
            List<ProvinceCityCounty> childrenCityList = cityList.stream().filter(city -> city.getParentId().equals(ProvinceCityCounty.getId())).collect(Collectors.toList());
            Optional.ofNullable(childrenCityList).orElse(new ArrayList<>()).forEach(cityCountry ->{
                List<ProvinceCityCounty> childrenCountryList =countryList.stream().filter(country -> country.getParentId().equals(cityCountry.getId())).collect(Collectors.toList());
                cityCountry.setProvinceCityCountyList(childrenCountryList);
            });
            ProvinceCityCounty.setProvinceCityCountyList(childrenCityList);
        });



        result.setData(provinceList);
        result.setCode(0);
        result.setMessage("成功");
        return result;
    }
}
